<?php
/**
 * Created by PhpStorm.
 * User: wangx08
 * Date: 2015-03-26
 * Time: 16:11
 */
namespace mybackend\controllers\common;

use Yii;
use common\error\ErrorCode;
use common\support\CFileUploader;
use common\support\OSSUploader;
use common\support\StringHelper;
use mybackend\controllers\BaseController;

/**
 * Class FileController
 * @package mybackend\controllers\common
 */
class FileController extends BaseController{


    /**
     * 根据配置区域不同的图片uploader对象
     * @param type $httpFile
     * @return \common\support\CFileUploader
     */
    private function getImageUploader($httpFile){
        $type = "file";
        $rootPath = "/upfiles";
        if(isset(Yii::$app->params["uploader"]) && isset(Yii::$app->params["uploader"]["type"])){
            $type = Yii::$app->params["uploader"]["type"];
            $rootPath = Yii::$app->params["uploader"]["rootPath"];
        }
        $uploader = null;
        $imageSize = 1024*1024*1; //图片大小限制为1M
        $contentType = [
            "image/gif","image/jpeg","image/pjpeg","image/png"
        ];
        if($type == 'oss'){
            $uploader = new OSSUploader($imageSize,$contentType,$httpFile,$rootPath);
        }
        else{
            $uploader = new CFileUploader($imageSize,$contentType,$httpFile,str_replace('\\','/',dirname(dirname(__DIR__)).'/web'),$rootPath);
        }
        return $uploader;
    }
    
    /**
     * 根据配置区域不同的文档uploader对象
     * @param type $httpFile
     * @return \common\support\CFileUploader
     */
    private function getDocumentUploader($httpFile){
        $type = "file";
        $rootPath = "/upfiles";
        if(isset(Yii::$app->params["uploader"]) && isset(Yii::$app->params["uploader"]["type"])){
            $type = Yii::$app->params["uploader"]["type"];
            $rootPath = Yii::$app->params["uploader"]["rootPath"];
        }
        $uploader = null;
        $imageSize = 1024*1024*20; //文档大小限制为20M
        $contentType = [];
        if($type == 'oss'){
            $uploader = new OSSUploader($imageSize,$contentType,$httpFile,$rootPath);
        }
        else{
            $uploader = new CFileUploader($imageSize,$contentType,$httpFile,str_replace('\\','/',dirname(dirname(__DIR__)).'/web'),$rootPath);
        }
        return $uploader;
    }    

    /**
     * /index.php?r=common/file/upload-image-with-thumb
     * request contains file named "file"
     * @return mixed
     */
    public function actionUploadImageWithThumb(){
        if(isset($_FILES["file"])){
            return $this->json(array(
                "retCode"=>199003,//无效的输入
            ));
        }
        $uploader = $this->getImageUploader($_FILES["file"]);
        if ($uploader->checkFileType()){
            if($uploader->checkFileSize()) {

                $url = $uploader->upload();

                return $this->json(array(
                    "retCode"=>ErrorCode::SUCCESS,
                    "data"=>array(
                        "path"=>$url,
                        "thumbPath"=>$url,
                    )
                ));
            }
            else{
                return $this->json(array(
                    "retCode"=>199001//文件超出10M大小限制
                ));
            }
        }
        else{
            return $this->json(array(
                "retCode"=>199002//文件不是正确的图片格式（gif,jpg,png）
            ));
        }
    }

    public function createImageThumb($source,$thumb){
    }

    /**
     * 图片上传
     * @return string
     */
    public function actionUploadImage(){
        $ret = $this->uploadImage("file");
        return $this->json($ret);
    }
    
    /**
     * 文档上传
     * @return string
     */
    public function actionUploadDocument(){
        $ret = $this->uploadDocument("file");
        return $this->json($ret);
    }    
   
     /**
      * UEditor搬到这里，只支持最简单的图片上传
      * @param $action
      * @return mixed
     */
    public function actionUeditor($action){
        $result = [
            "state"=> "未知的请求",
        ];
        switch ($action) {
            case 'config':
                $result =  [
                    "imageActionName"=> "uploadimage", /* 执行上传图片的action名称 */
                    "imageFieldName"=> "upfile", /* 提交的图片表单名称 */
                    "imageMaxSize"=> 1024000, /* 上传大小限制1M，单位B */
                    "imageAllowFiles"=> [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
                    "imageCompressEnable"=> true, /* 是否压缩图片,默认是true */
                    "imageCompressBorder"=> 1600, /* 图片压缩最长边限制 */
                    "imageInsertAlign"=> "none", /* 插入的图片浮动方式 */
                    "imageUrlPrefix"=> "", /* 图片访问路径前缀 */
                ];
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->uploadImage("upfile");
                if($result["retCode"] == ErrorCode::SUCCESS){
                    $result = [
                        "state"=> "SUCCESS",
                        "url"=> $result["data"]["path"],
                        "title"=> "",
                        "original"=> ""
                    ];
                }else{
                    $result = [
                        "state"=>"上传失败"
                    ];
                }
                break;
            /* 列出图片 */
            case 'listimage':
            /* 列出文件 */
            case 'listfile':
            /* 抓取远程文件 */
            case 'catchimage':
                break;
            default:
                $result = [
                    "state"=> "不支持",
                ];
                break;
        }
        return $this->json($result);
    }
    
    /**
     * 上传图片
     * @param type $fieldName
     * @return type
     */
    private function uploadImage($fieldName){
        if(!isset($_FILES[$fieldName])){
            return array(
                    "retCode"=>199003,//无效的输入
                    "errMsg"=>"请上传文件"
                );
        }
        $uploader = $this->getImageUploader($_FILES[$fieldName]);
        //检测文件格式
        if(!$uploader->checkFileType()){
            return array(
                "retCode"=>199002,
                "errMsg"=>"文件格式不正确"
            );
        }
        //检测文件大小
        if(!$uploader->checkFileSize()){
            return array(
                "retCode"=>199001,//文件超出1M大小限制
                "errMsg"=>"文件大小不能超过1M"
            );
        }
        
        $url = $uploader->upload();
        return array(
                "retCode"=>ErrorCode::SUCCESS,
                "data"=>array(
                    "path"=>urldecode($url),
                )
            );
    }

    /**
     * 上传文档
     * @param type $fieldName
     * @return type
     */
    private function uploadDocument($fieldName){
        if(!isset($_FILES[$fieldName])){
            return array(
                    "retCode"=>199003,//无效的输入
                    "errMsg"=>"无上传数据，原因可能是文件大小超出php.ini的post_max_size设置值。"
                );
        }

        if($_FILES["file"]["error"]>0){
            $error_msg = '';
            switch ($_FILES["file"]["error"])
            {
                case 1:
                  $error_msg = '上传文件大小超过php.ini中upload_max_filesize 选项限制的值';
                  break;  
                case 2:
                  $error_msg = '上传文件大小超过 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
                  break;
                case 3:
                  $error_msg = '文件只有部分被上传';
                  break;  
                case 4:
                  $error_msg = '没有文件被上传';
                  break;
                default:
                  $error_msg = '错误码为'.$_FILES["file"]["error"];
            }
            return array(
                    "retCode"=>199003,//无效的输入
                    "errMsg"=>$error_msg
                );
        }    
        
        $uploader = $this->getDocumentUploader($_FILES[$fieldName]);
        //检测文件格式
        if(!$uploader->checkFileType()){
            return array(
                "retCode"=>199002,
                "errMsg"=>"文件格式不正确"
            );
        }
        //检测文件大小
        if(!$uploader->checkFileSize()){
            return array(
                "retCode"=>199001,//文件超出大小限制
                "errMsg"=>"文件大小不能超过20M"
            );
        }
        
        $url = $uploader->upload();
        return array(
                "retCode"=>ErrorCode::SUCCESS,
                "data"=>array(
                    "path"=>urldecode($url),
                )
            );
    }    
    
    /**
     * 重定基类json方法，如果客户不支持application/json头，则返回content-type:text/plain
     * @param type $data
     * @param type $sucess
     * @return type
     */
    protected function json($data,$success = true)
    {
        $accept = $_SERVER['HTTP_ACCEPT'];
        if (strpos($accept, 'application/json') === false) {
            echo json_encode($data);
        } else {
           return parent::json($data,$success);
        }
    }
}